import Taro from '@tarojs/taro'
import { Feedback, FeedbackType, FeedbackStatus, DishRating, Dish, User } from '../types'
import { CloudDataManager } from './cloud'

// 反馈工具类
export class FeedbackUtils {
  /**
   * 创建新反馈
   * @param feedback 反馈信息
   * @returns Promise<string> 反馈ID
   */
  static async createFeedback(feedback: Omit<Feedback, 'id' | 'status' | 'createdAt' | 'updatedAt'>): Promise<string> {
    try {
      // 准备反馈数据
      const now = new Date()
      const newFeedback: Feedback = {
        ...feedback,
        id: `feedback_${Date.now()}`,
        status: 'pending',
        createdAt: now,
        updatedAt: now
      }
      
      // 保存到云数据库
      const feedbackId = await CloudDataManager.addData('feedbacks', newFeedback)
      
      // 显示成功提示
      Taro.showToast({
        title: '反馈提交成功',
        icon: 'success'
      })
      
      return feedbackId
    } catch (error) {
      console.error('创建反馈失败:', error)
      Taro.showToast({
        title: '反馈提交失败',
        icon: 'error'
      })
      throw error
    }
  }

  /**
   * 更新反馈状态
   * @param feedbackId 反馈ID
   * @param status 新状态
   * @param response 回复内容
   * @returns Promise<boolean>
   */
  static async updateFeedbackStatus(feedbackId: string, status: FeedbackStatus, response?: string): Promise<boolean> {
    try {
      // 获取反馈信息
      const feedbacks = await CloudDataManager.getAllData('feedbacks')
      const feedback = feedbacks.find(f => f.id === feedbackId)
      
      if (!feedback) {
        throw new Error('反馈不存在')
      }
      
      // 更新反馈状态
      const updatedFeedback = {
        ...feedback,
        status,
        response: response || feedback.response,
        updatedAt: new Date()
      }
      
      await CloudDataManager.updateData('feedbacks', feedbackId, updatedFeedback)
      
      // 显示成功提示
      Taro.showToast({
        title: '反馈状态已更新',
        icon: 'success'
      })
      
      return true
    } catch (error) {
      console.error('更新反馈状态失败:', error)
      Taro.showToast({
        title: '更新失败',
        icon: 'error'
      })
      throw error
    }
  }

  /**
   * 获取用户反馈
   * @param userId 用户ID
   * @returns Promise<Feedback[]>
   */
  static async getUserFeedbacks(userId: string): Promise<Feedback[]> {
    try {
      const feedbacks = await CloudDataManager.getAllData('feedbacks', { userId })
      return feedbacks.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    } catch (error) {
      console.error('获取用户反馈失败:', error)
      return []
    }
  }

  /**
   * 获取所有反馈
   * @param status 状态筛选
   * @returns Promise<Feedback[]>
   */
  static async getAllFeedbacks(status?: FeedbackStatus): Promise<Feedback[]> {
    try {
      const query = status ? { status } : {}
      const feedbacks = await CloudDataManager.getAllData('feedbacks', query)
      return feedbacks.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    } catch (error) {
      console.error('获取反馈列表失败:', error)
      return []
    }
  }

  /**
   * 添加菜品评价
   * @param rating 评价信息
   * @returns Promise<string> 评价ID
   */
  static async addDishRating(rating: Omit<DishRating, 'id' | 'createdAt'>): Promise<string> {
    try {
      // 准备评价数据
      const newRating: DishRating = {
        ...rating,
        id: `rating_${Date.now()}`,
        createdAt: new Date()
      }
      
      // 保存到云数据库
      const ratingId = await CloudDataManager.addData('ratings', newRating)
      
      // 更新菜品的平均评分
      await this.updateDishAverageRating(rating.dishId)
      
      // 显示成功提示
      Taro.showToast({
        title: '评价提交成功',
        icon: 'success'
      })
      
      return ratingId
    } catch (error) {
      console.error('添加评价失败:', error)
      Taro.showToast({
        title: '评价提交失败',
        icon: 'error'
      })
      throw error
    }
  }

  /**
   * 获取菜品评价
   * @param dishId 菜品ID
   * @returns Promise<DishRating[]>
   */
  static async getDishRatings(dishId: string): Promise<DishRating[]> {
    try {
      const ratings = await CloudDataManager.getAllData('ratings', { dishId })
      return ratings.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    } catch (error) {
      console.error('获取菜品评价失败:', error)
      return []
    }
  }

  /**
   * 获取用户评价
   * @param userId 用户ID
   * @returns Promise<DishRating[]>
   */
  static async getUserRatings(userId: string): Promise<DishRating[]> {
    try {
      const ratings = await CloudDataManager.getAllData('ratings', { userId })
      return ratings.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    } catch (error) {
      console.error('获取用户评价失败:', error)
      return []
    }
  }

  /**
   * 更新菜品平均评分
   * @param dishId 菜品ID
   * @returns Promise<boolean>
   */
  static async updateDishAverageRating(dishId: string): Promise<boolean> {
    try {
      // 获取菜品所有评价
      const ratings = await this.getDishRatings(dishId)
      
      if (ratings.length === 0) {
        return false
      }
      
      // 计算平均分
      const totalRating = ratings.reduce((sum, rating) => sum + rating.rating, 0)
      const averageRating = totalRating / ratings.length
      
      // 获取菜品信息
      const dishes = await CloudDataManager.getDishes()
      const dish = dishes.find(d => d.id === dishId)
      
      if (!dish) {
        return false
      }
      
      // 更新菜品评分信息
      const updatedDish = {
        ...dish,
        averageRating: parseFloat(averageRating.toFixed(1)),
        ratingCount: ratings.length,
        updatedAt: new Date()
      }
      
      await CloudDataManager.saveDish(updatedDish)
      return true
    } catch (error) {
      console.error('更新菜品评分失败:', error)
      return false
    }
  }

  /**
   * 格式化反馈类型
   * @param type 反馈类型
   * @returns 格式化后的类型文本
   */
  static formatFeedbackType(type: FeedbackType): string {
    const typeMap: Record<FeedbackType, string> = {
      suggestion: '建议',
      bug: '问题',
      complaint: '投诉',
      praise: '表扬'
    }
    return typeMap[type]
  }

  /**
   * 格式化反馈状态
   * @param status 反馈状态
   * @returns 格式化后的状态文本
   */
  static formatFeedbackStatus(status: FeedbackStatus): string {
    const statusMap: Record<FeedbackStatus, string> = {
      pending: '待处理',
      processing: '处理中',
      resolved: '已解决',
      rejected: '已拒绝'
    }
    return statusMap[status]
  }

  /**
   * 获取反馈状态颜色
   * @param status 反馈状态
   * @returns 状态颜色
   */
  static getFeedbackStatusColor(status: FeedbackStatus): string {
    const colorMap: Record<FeedbackStatus, string> = {
      pending: '#ff9500',
      processing: '#007aff',
      resolved: '#34c759',
      rejected: '#ff3b30'
    }
    return colorMap[status]
  }

  /**
   * 获取评分文本
   * @param rating 评分
   * @returns 评分文本
   */
  static getRatingText(rating: number): string {
    const ratingMap: Record<number, string> = {
      1: '很差',
      2: '较差',
      3: '一般',
      4: '不错',
      5: '很好'
    }
    return ratingMap[rating] || ''
  }
}

// 导出工具函数
export const feedbackUtils = {
  createFeedback: FeedbackUtils.createFeedback,
  updateFeedbackStatus: FeedbackUtils.updateFeedbackStatus,
  getUserFeedbacks: FeedbackUtils.getUserFeedbacks,
  getAllFeedbacks: FeedbackUtils.getAllFeedbacks,
  addDishRating: FeedbackUtils.addDishRating,
  getDishRatings: FeedbackUtils.getDishRatings,
  getUserRatings: FeedbackUtils.getUserRatings,
  updateDishAverageRating: FeedbackUtils.updateDishAverageRating,
  formatFeedbackType: FeedbackUtils.formatFeedbackType,
  formatFeedbackStatus: FeedbackUtils.formatFeedbackStatus,
  getFeedbackStatusColor: FeedbackUtils.getFeedbackStatusColor,
  getRatingText: FeedbackUtils.getRatingText
} 